<?php
/**
 * 系统路由器
 */
class Lin_Router
{
	private $_request; 
	
	public function __construct()
	{
		$this->_request = Lin_Request::getInstance();
	}
	
	/**
	 * 获取控制器的文件地址
	 */
	private function getController()
	{
		$ctl  = APPLICATION_PATH . "/modules/" . ucfirst($this->_request->getModel()) . '/controllers/' . ucfirst($this->_request->getController()) . 'Controller.php';
		return $ctl;		
	}
	
	/**
	 * 获取控制器类名
	 */
	private function getControllerName()
	{
		$className = ucfirst($this->_request->getModel()) . '_' . ucfirst($this->_request->getController()) . 'Controller';
		return $className;
	}
	
	/**
	 * 获取待执行的方法
	 */
	private function getActionName()
	{
		$actionName = $this->_request->getAction() . 'Action';
		return $actionName;
	}
	
	/*
	 * 执行路由
	 */
	public function run()
	{
		if (!file_exists($this->getController()))
		{
			die("<p>This file[" . $this->getController() . "] does not existed!</p>");
		}
		require_once ($this->getController());
		
		$controller = $this->getControllerName();
		$action = $this->getActionName();
		
		if (!class_exists($controller))
		{
			die("<p>Cann't get class[{$controller}]!</p>");
		}
		$obj = new $controller();
		
		//Bootstrap
		$bootstrap = new Lin_Bootstrap();
		$bootstrap->boot($obj);		
		
		if (!method_exists($obj, $action))
		{
			die("<p>Cann't get method[{$action}]</p>");
		}
		$obj->$action();
		
		if (method_exists($obj, 'template'))
		{
			$obj->template();
		}
		exit;
	}
}

